package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.ServiceCapability;
import com.huaweicloud.sdk.iotda.v5.model.ShowProductRequest;
import com.huaweicloud.sdk.iotda.v5.model.ShowProductResponse;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IAlertDataService;
import com.zzyl.system.mapper.SysUserRoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.AlertRuleMapper;
import com.zzyl.nursing.domain.AlertRule;
import com.zzyl.nursing.service.IAlertRuleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 报警规则Service业务层处理
 * 
 * @author alexis
 * @date 2025-06-09
 */
@Slf4j
@Service
public class AlertRuleServiceImpl extends ServiceImpl<AlertRuleMapper, AlertRule> implements IAlertRuleService
{
    @Autowired
    private AlertRuleMapper alertRuleMapper;
    @Autowired
    private IoTDAClient ioTDAClient;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Value("${alert.deviceMaintainerRole}")
    private String deviceMaintainerRole;

    @Value("${alert.deviceMaintainerRole}")
    private String managerRole;

    @Autowired
    private IAlertDataService alertDataService;

    /**
     * 查询报警规则
     * 
     * @param id 报警规则主键
     * @return 报警规则
     */
    @Override
    public AlertRule selectAlertRuleById(Long id)
    {
        return alertRuleMapper.selectById(id);
    }

    /**
     * 查询报警规则列表
     * 
     * @param alertRule 报警规则
     * @return 报警规则
     */
    @Override
    public List<AlertRule> selectAlertRuleList(AlertRule alertRule)
    {
        return alertRuleMapper.selectAlertRuleList(alertRule);
    }

    /**
     * 新增报警规则
     * 
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int insertAlertRule(AlertRule alertRule)
    {
        return alertRuleMapper.insert(alertRule);
    }

    /**
     * 修改报警规则
     * 
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int updateAlertRule(AlertRule alertRule)
    {
        return alertRuleMapper.updateById(alertRule);
    }

    /**
     * 批量删除报警规则
     * 
     * @param ids 需要删除的报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleByIds(Long[] ids)
    {
        return alertRuleMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除报警规则信息
     * 
     * @param id 报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleById(Long id)
    {
        return alertRuleMapper.deleteById(id);
    }

    /**
     * 报警规则过滤定时任务
     */
    @Override
    public void alertFilter() {
        //查询所有规则，遍历规则
        // 查询状态为1（例如：启用或激活状态）的AlertRule记录总数
        Long count = lambdaQuery().eq(AlertRule::getStatus, 1).count();

        // 如果没有找到任何状态为1的记录，则不执行任何操作并退出方法
        if (count <= 0) {
            return;
        }

        //查询所有设备上报的最新数据
        List<Object> list = redisTemplate.opsForHash().values(CacheConstants.IOT_DEVICE_LAST_DATA);
        if (CollUtil.isEmpty(list)) {
            return;
        }
        //解析上报的数据
        ArrayList<DeviceData> deviceDataList = new ArrayList<>();
        list.forEach(d -> {
            List<DeviceData> dataList = JSONUtil.toList(d.toString(), DeviceData.class);
            deviceDataList.addAll(dataList);
        });

        //获取报警规则，进行匹配
        deviceDataList.forEach(d -> alertFilter(d));
    }

    /**
     * 逐条过滤报警数据
     * @param deviceData
     */
    private void alertFilter(DeviceData deviceData) {
        //判断当前上报的数据是否超过了1分钟
        LocalDateTime alarmTime = deviceData.getAlarmTime();
        long between = LocalDateTimeUtil.between(alarmTime, LocalDateTime.now(), ChronoUnit.SECONDS);

        if (between > 60) {
            // 数据已超过1分钟，可以记录日志或进行其他处理
            return;
        }

        //查询所有产品的规则和该物模型的规则
        List<AlertRule> allRules = lambdaQuery()
                .eq(AlertRule::getProductKey, deviceData.getProductKey())
                .eq(AlertRule::getFunctionId, deviceData.getFunctionId())
                .eq(AlertRule::getIotId, "-1")
                .eq(AlertRule::getStatus, 1)
                .list();


        List<AlertRule> iotIdRules = lambdaQuery()
                .eq(AlertRule::getProductKey, deviceData.getProductKey())
                .eq(AlertRule::getFunctionId, deviceData.getFunctionId())
                .eq(AlertRule::getIotId, deviceData.getIotId())
                .eq(AlertRule::getStatus, 1)
                .list();
        //合并
        Collection<AlertRule> allAlertRules = CollUtil.addAll(allRules, iotIdRules);
        //如果为空，则中断
        if (CollUtil.isEmpty(allAlertRules)) {
            return;
        }

        //按照过滤规则和上报的数据进行匹配
        allAlertRules.forEach(alertRule -> deviceDataAlarmHandler(alertRule, deviceData));

    }

    /**
     * 设备数据处理,过滤数据是否触发报警规则
     * @param alertRule
     * @param deviceData
     */
    private void deviceDataAlarmHandler(AlertRule alertRule, DeviceData deviceData) {
        //判断上报时间是否在规则的生效时间内
        String[] split = alertRule.getAlertEffectivePeriod().split("~");
        LocalTime startTime = LocalTime.parse(split[0]);
        LocalTime endTime = LocalTime.parse(split[1]);
        //获取上报时间
        LocalTime alarmTime = LocalDateTimeUtil.of(deviceData.getAlarmTime()).toLocalTime();

        //不在上报时间内，则结束请求
        if (alarmTime.isBefore(startTime) || alarmTime.isAfter(startTime)) {
            return;
        }
        //获取IOTID
        String iotId = deviceData.getIotId();

        //统计次数key
        String key = CacheConstants.ALERT_TRIGGER_COUNT_PREFIX + iotId + ":" + deviceData.getFunctionId() + ":" + alertRule.getId();
        //数据对比，上报的数据与规则中的阈值进行对比
        int compare = NumberUtil.compare(Double.valueOf(deviceData.getDataValue()), alertRule.getValue());
        //判断是否满足条件
        if ((alertRule.getOperator().equals(">=") && compare >= 0) || (alertRule.getOperator().equals("<") && compare < 0)) {
            log.info("当前上报的数据符合规则异常");
        } else {
            redisTemplate.delete(key);
            return;
        }

        //进来异常的数据，判断是否在沉默周期内
        String silentKey = CacheConstants.ALERT_SILENT_PREFIX + iotId + ":" + deviceData.getFunctionId() + ":" + alertRule.getId();
        String silentData = redisTemplate.opsForValue().get(silentKey);
        if(StringUtils.isNotEmpty(silentData)) {
            return;
        }

        //持续周期逻辑
        String data = redisTemplate.opsForValue().get(key);
        //获取当前次数
        int count = StringUtils.isEmpty(data) ? 1 : Integer.parseInt(data) + 1;
        //count和持续周期的值相等，则触发报警
        if (ObjectUtil.notEqual(count, alertRule.getDuration())) {
            //不相等
            redisTemplate.opsForValue().set(key, count + "");
            return;
        }
        //删除redis中的数据
        redisTemplate.delete(key);
        //存储数据到沉默周期，设置一个过期时间，规则中的沉默周期
        redisTemplate.opsForValue().set(silentKey, "1", alertRule.getAlertSilentPeriod(), TimeUnit.MINUTES);
        
        //报警数据时需要找到对应的人 老人，护理员，维修工，超级管理员
        List<Long> userIds = new ArrayList<>();
        if (alertRule.getAlertDataType().equals(0)) {
            //老人异常数据
            if (deviceData.getLocationType().equals(0)) {
                //说明是随身设备，直接可以找到老人的id，找到对应的护理员
                userIds = deviceMapper.selectNursingIdsByIotIdWithElder(iotId);
            } else if (deviceData.getLocationType().equals(1) && deviceData.getPhysicalLocationType().equals(2)) {
                //固定设备，床位->老人->护理员
                userIds = deviceMapper.selectNursingIdsByIotIdWithBed(iotId);
            } else {
                //设备异常数据，找维修工...
                userIds = sysUserRoleMapper.selectUserIdByRoleName(deviceMaintainerRole);
            }
            //不管哪种情况，都需要通知超级管理员
            List<Long> managerIds = sysUserRoleMapper.selectUserIdByRoleName(managerRole);
            Collection<Long> allUserIds = CollUtil.addAll(userIds, managerIds);

            //去重
            allUserIds = CollUtil.distinct(allUserIds);

            //保存报警数据
            insertAlertData(allUserIds, alertRule, deviceData);
        }
    }

    /**
     * 保存报警数据
     * @param allUserIds
     * @param alertRule
     * @param deviceData
     */
    private void insertAlertData(Collection<Long> allUserIds, AlertRule alertRule, DeviceData deviceData) {
        //对象拷贝
        AlertData alertData = BeanUtil.toBean(deviceData, AlertData.class);
        alertData.setAlertRuleId(alertRule.getId());
        //心率<65,持续3个周期就报警
        String alertReason = CharSequenceUtil.format("{}{}{},持续{}个周期就报警", alertRule.getFunctionName(), alertRule.getOperator(), alertRule.getValue(), alertRule.getDuration());
        alertData.setAlertReason(alertReason);
        alertData.setStatus(0);
        alertData.setType(alertRule.getAlertDataType());

        //遍历allUserIds
        List<AlertData> list = allUserIds.stream().map(userId -> {
            AlertData dbAlertData = BeanUtil.toBean(alertData, AlertData.class);
            dbAlertData.setUserId(userId);
            dbAlertData.setId(null);
            return dbAlertData;
        }).collect(Collectors.toList());

        //批量保存
        alertDataService.saveBatch(list);
    }


}
